using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using Sixeyed.CacheAdapter.Interfaces;

namespace Sixeyed.CacheAdapter.Management.Dialogs
{
	/// <summary>
	/// Dialog for configuring an instance of a cache
	/// </summary>
	public class CacheProviderConfiguration : System.Windows.Forms.Form
	{
		private bool loaded;
		private System.Windows.Forms.Button okButton;
        private System.Windows.Forms.PropertyGrid propertyGrid;
        private System.Windows.Forms.Button cancelButton;
		private System.ComponentModel.Container components = null;

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CacheProviderConfiguration));
            this.okButton = new System.Windows.Forms.Button();
            this.propertyGrid = new System.Windows.Forms.PropertyGrid();
            this.cancelButton = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // okButton
            // 
            this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.okButton.Location = new System.Drawing.Point(223, 288);
            this.okButton.Name = "okButton";
            this.okButton.Size = new System.Drawing.Size(75, 23);
            this.okButton.TabIndex = 0;
            this.okButton.Text = "OK";
            this.okButton.Click += new System.EventHandler(this.okButton_Click);
            // 
            // propertyGrid
            // 
            this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.propertyGrid.LineColor = System.Drawing.SystemColors.ScrollBar;
            this.propertyGrid.Location = new System.Drawing.Point(12, 12);
            this.propertyGrid.Name = "propertyGrid";
            this.propertyGrid.PropertySort = System.Windows.Forms.PropertySort.Categorized;
            this.propertyGrid.Size = new System.Drawing.Size(367, 261);
            this.propertyGrid.TabIndex = 1;
            this.propertyGrid.ToolbarVisible = false;
            // 
            // cancelButton
            // 
            this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.cancelButton.Location = new System.Drawing.Point(304, 288);
            this.cancelButton.Name = "cancelButton";
            this.cancelButton.Size = new System.Drawing.Size(75, 23);
            this.cancelButton.TabIndex = 4;
            this.cancelButton.Text = "Cancel";
            // 
            // CacheProviderConfiguration
            // 
            this.AcceptButton = this.okButton;
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.CancelButton = this.cancelButton;
            this.ClientSize = new System.Drawing.Size(387, 319);
            this.Controls.Add(this.cancelButton);
            this.Controls.Add(this.propertyGrid);
            this.Controls.Add(this.okButton);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "CacheProviderConfiguration";
            this.ShowInTaskbar = false;
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Cache Provider Configuration";
            this.Load += new System.EventHandler(this.TaskDialog_Load);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// Default constructor
        /// </summary>
		public CacheProviderConfiguration()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			loaded = false;
            if (string.IsNullOrEmpty(TransmitLocation.Current.Provider))
            {
                MessageBox.Show("Cache Provider must be specified before configuring", "Cache Adapter");
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
		}

		/// <summary>
		/// Clean up resources
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		private void TaskDialog_Load(object sender, System.EventArgs e)
		{
            this.LoadPropertyGrid();
		}

        private void LoadPropertyGrid()
        {
            if (!loaded)
            {                
                object configuration;
                
                if (!string.IsNullOrEmpty(TransmitLocation.Current.Configuration))
                {
                    StringReader reader = new StringReader(TransmitLocation.Current.Configuration);
                    XmlSerializer configSerializer = TransmitLocation.Current.GetCacheConfigurationSerializer();
                    configuration = configSerializer.Deserialize(reader);
                }
                else
                {
                    configuration = Activator.CreateInstance(TransmitLocation.Current.GetCacheConfigurationType());
                }
                propertyGrid.SelectedObject = configuration;
                loaded = true;
            }
        }        

        private void okButton_Click(object sender, EventArgs e)
        {
            string xml = string.Empty;
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer configSerializer = TransmitLocation.Current.GetCacheConfigurationSerializer();
                configSerializer.Serialize(stream, propertyGrid.SelectedObject);
                stream.Position = 0;
                StreamReader reader = new StreamReader(stream);
                xml = reader.ReadToEnd();
            }
            TransmitLocation.Current.Configuration = xml;
        }
	}
}
